package com.emapp.lccode.db

import android.content.Context
import androidx.room.Database
import androidx.room.Room.databaseBuilder
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.emapp.lccode.base.BaseApplication
import com.emapp.lccode.bean.User
import com.emapp.lccode.bean.UserKt
import com.emapp.lccode.db.AppDatabase

@Database(entities = [UserKt::class], version = AppDatabase.VERSION)
abstract class AppDatabase : RoomDatabase() {
    abstract val userDao: UserDao?

    companion object {
        const val VERSION = 1
        const val SYMBOL = "@@@"

        @Volatile
        private var instance: AppDatabase? = null
        @JvmStatic
        @Synchronized
        fun get(): AppDatabase? {
            if (instance == null) instance = create(BaseApplication.instance)
            return instance
        }

        private fun create(context: Context): AppDatabase {
            return databaseBuilder(context, AppDatabase::class.java, "dm_farmland0")
                //.addMigrations(MIGRATION_11_12)
                //.addMigrations(MIGRATION_12_13)
                .allowMainThreadQueries()
                .fallbackToDestructiveMigration()
                .build()
        }

        val MIGRATION_11_12: Migration = object : Migration(11, 12) {
            override fun migrate(database: SupportSQLiteDatabase) {
                database.execSQL("ALTER TABLE History ADD COLUMN scale INTEGER DEFAULT -1 NOT NULL")
            }
        }
        val MIGRATION_12_13: Migration = object : Migration(12, 13) {
            override fun migrate(database: SupportSQLiteDatabase) {
                database.execSQL("ALTER TABLE History ADD COLUMN speed REAL DEFAULT 1 NOT NULL")
                database.execSQL("ALTER TABLE History ADD COLUMN player INTEGER DEFAULT -1 NOT NULL")
            }
        }
    }
}